package erlwitch.parser;

import java.io.Reader;

import java_cup.runtime.ComplexSymbolFactory;
import erlwitch.parser.reader.SpecialReader;
import erlwitch.parser.structure.Module;

public class Parser {
	public static Module parseFile(String path) throws ParserException {
		ErlangScanner scanner = null;
		ErlangParser parser = null;
		try {
			Reader reader = new SpecialReader(
				new java.io.FileReader(path)
			);
			scanner = new ErlangScanner(reader,	new ComplexSymbolFactory());
			parser = new ErlangParser(scanner);
			parser.parse();
			ParserListener l = parser.getListener();
			l.toString();
			
			String moduleName = l.getModuleName();
			Module ret = new Module(moduleName, l.getFunList());
			return ret;
		} catch (java.io.FileNotFoundException e) {
			throw new ParserException("File not found : \"" + path + "\"", e);
		} catch (java.io.IOException e) {
			throw new ParserException("IO error scanning file \"" + path + "\"", e);
		} catch (Exception e) {
			throw new ParserException("Unexpected exception on \"" + path + "\"", e);
		}
	}

	public static Module parse(String text) throws ParserException {
		ErlangScanner scanner = null;
		ErlangParser parser = null;
		try {
			Reader reader = new SpecialReader(
				new java.io.StringReader(text)
			);
			scanner = new ErlangScanner(reader,	new ComplexSymbolFactory());
			parser = new ErlangParser(scanner);
			parser.parse();
			ParserListener l = parser.getListener();
			l.toString();
			
			String moduleName = l.getModuleName();
			Module ret = new Module(moduleName, l.getFunList());
			return ret;
		} catch (java.io.IOException e) {
			throw new ParserException("IO error scanning text", e);
		} catch (Exception e) {
			throw new ParserException("Unexpected exception parsing text", e);
		}
	}
}
